//
//  HomeViewController.swift
//  DS11WB
//
//  Created by 白鹭 on 16/4/1.
//  Copyright © 2016年 bailun91. All rights reserved.
//

import UIKit
import SDWebImage
import MJRefresh
class HomeViewController: BaseViewController {

    
    @IBOutlet weak var tableView: UITableView!
    fileprivate lazy var titleBtn:TitleButton = TitleButton()
    // 数据源
    fileprivate lazy var statuses:[StatuesViewModel] = [StatuesViewModel]()
    fileprivate lazy var tipLabel : UILabel = UILabel()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        vtView.addRotationAnim();
        if !isLogin {
            return
        }
        //设置导航栏
        setupNavigationBar()
        
        //设置tableViewCell高度(根据内容自适应高度)
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 300;
        
        
        // 4.布局刷新控件
        setupHeaderView()
        setupFooterView()
        
        // 5.设置提示的Label
        setupTipLabel()
        
        //6.监听通知
        setupNatifications()
    }
    
}

// MARK:- 设置UI
extension HomeViewController{
    
     func setupNavigationBar() {
        
        // 1.设置左侧的Item
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: "navigationbar_friendattention")
        
        // 2.设置右侧的Item
        navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: "navigationbar_pop")
        
        //3. 设置标题按钮
        titleBtn.setTitle("bailun91", for: UIControlState())
        titleBtn.addTarget(self, action:#selector(HomeViewController.titleBtnClick), for: .touchUpInside)
        navigationItem.titleView = titleBtn
    }
    
    // MARK:-设置刷新控件
    func setupHeaderView(){
        
        let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction:#selector(HomeViewController.loadNewStatuses))
        
        header?.setTitle("下拉刷新数据", for: .idle)
        header?.setTitle("释放更新", for: .pulling)
        header?.setTitle("加载中", for: .refreshing)

        tableView.mj_header = header
        tableView.mj_header.beginRefreshing()
    }
    
    func setupFooterView(){
        
        tableView.mj_footer = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction:#selector(HomeViewController.loadMoreStatuses)
        )
    }
    
    
    func setupTipLabel() {
        
        // 1.将tipLabel添加父控件中
        navigationController?.navigationBar.insertSubview(tipLabel, at: 0)
        
        // 2.设置tipLabel的frame
        tipLabel.frame = CGRect(x: 0, y: 10, width: UIScreen.main.bounds.width, height: 32)
        
        // 3.设置tipLabel的属性
        tipLabel.backgroundColor = UIColor.orange
        tipLabel.textColor = UIColor.white
        tipLabel.font = UIFont.systemFont(ofSize: 14)
        tipLabel.textAlignment = .center
        tipLabel.isHidden = true
    }
}

extension HomeViewController{
    
    func setupNatifications(){
        
        NotificationCenter.default.addObserver(self, selector:#selector(HomeViewController.showPhotoBrowser(_:)), name: NSNotification.Name(rawValue: ShowPhotoBrowserNote), object: nil)
    }

    

}

// MARK:- 按钮监听
extension HomeViewController{
    
     @objc fileprivate func titleBtnClick(_ titleBtn : TitleButton) {
        // 1.改变按钮的状态
        titleBtn.isSelected = !titleBtn.isSelected
    }
    
    @objc  fileprivate func showPhotoBrowser(_ note: NSNotification){

        // 0.取出数据
        let indexPath = note.userInfo![ShowPhotoBrowserIndexKey]
        let picURLs = note.userInfo![ShowPhotoBrowserUrlsKey]
        
        print(indexPath!)
        print(picURLs!)
        // 1.创建控制器
        let photoBrowserVc = PhotoBrowserController(indexPath: indexPath as! NSIndexPath, picURLs: picURLs as! [URL])
        
        // 2.以modal的形式弹出控制器
        present(photoBrowserVc, animated: true, completion: nil)
    }
}


// MARK:- 请求网络数据

extension HomeViewController{
    
    /// 加载最新的数据
    @objc fileprivate func loadNewStatuses() {
        loadStatuses(isNewData: true)
    }
    
    /// 加载最新的数据
    @objc fileprivate func loadMoreStatuses() {
        loadStatuses(isNewData: false)
    }
    
    
  fileprivate  func loadStatuses(isNewData : Bool) {
    
    // 1.获取since_id/max_id
    var since_id = 0
    var max_id = 0
    if isNewData {
        since_id = statuses.first?.status?.mid ?? 0
    } else {
        max_id = statuses.last?.status?.mid ?? 0
        max_id = max_id == 0 ? 0 : (max_id - 1)
    }
    
    NETWorkTool.sharedNETWorkTool.loadStatuses(since_id: since_id, max_id: max_id) { (result, error) in
   
        // 1.错误校验
        if error != nil {
            print(error!)
            return
        }

        // 2.获取可选类型中的数据
        guard let resultArray = result else {
            return
        }
        
        var tempViewModel = [StatuesViewModel]()
        for statusDict in resultArray {
            let status = statuesModel(dict: statusDict)
            let viewModel = StatuesViewModel(status: status)
            tempViewModel.append(viewModel)
        }
        
        // 4.将数据放入到成员变量的数组中
        if isNewData {
            self.statuses = tempViewModel + self.statuses
        } else {
            self.statuses += tempViewModel
        }
        
        // 5.缓存图片
        self.cacheImages(viewModels: tempViewModel)
        
    }
    
    
    }
    // MARK:- 下载图片
    fileprivate func cacheImages(viewModels:[StatuesViewModel]){
        
        let group = DispatchGroup()//创建队列
        
        for viewModel in viewModels {
            for picURL in viewModel.picURLs {
                group.enter()
                SDWebImageManager.shared().loadImage(with: picURL, options: [], progress: nil, completed: { (_, _, _, _, _, _) in
                group.leave()
                })
            }
        }
        
        group.notify(queue: DispatchQueue.main) {
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            self.showTipLabel(count: viewModels.count)
            self.tableView.reloadData()
            
        }
    }
    /// 显示提示的Label
    fileprivate func showTipLabel(count : Int) {
        // 1.设置tipLabel的属性
        tipLabel.isHidden = false
        tipLabel.text = count == 0 ? "没有新数据" : "\(count) 条新微博"
        
        // 2.执行动画
        UIView.animate(withDuration: 1.0, animations: { () -> Void in
            self.tipLabel.frame.origin.y = 44
        }) { (_) -> Void in
            UIView.animate(withDuration: 1.0, delay: 1.5, options: [], animations: { () -> Void in
                self.tipLabel.frame.origin.y = 10
            }, completion: { (_) -> Void in
                self.tipLabel.isHidden = true
            })
        }
    }

    
    
}


// MARK:- UITableViewDataSource

extension HomeViewController:UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statuses.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // 1.创建cell
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell") as! HomeViewCell
        
        // 2.给cell设置数据
        
        cell.viewModel = statuses[indexPath.row]
        
        return cell
        
    }
}

// MARK:- UITableViewDelegate代理
extension HomeViewController:UITableViewDelegate{
    
}
